﻿using ByrForumAPI.MetaData;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ByrForumAPI.Entity
{
    public class UserEntity
    {
        private User user;
        
        public User User
        {
            get
            {
                return this.user;
            }
        }

        public UserEntity(string id)
        {
            OAuth oAuth = new OAuth();
            string userQueryRequestUrl = string.Format("/user/query/{0}.json", id);
            try
            {
                string response = oAuth.Request(userQueryRequestUrl);
                this.user = JsonConvert.DeserializeObject<User>(response);
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("Get user:{0} error: {1}", id, e.Message));
            }
        }

        public bool UserLogin(string userId, string password)
        {
            OAuth oAuth = new OAuth(userId, password);
            string userQueryRequestUrl = string.Format("/user/login.json");
            try
            {
                string response = oAuth.Request(userQueryRequestUrl);
                User result = JsonConvert.DeserializeObject<User>(response);
                if (string.Equals(result.ID, userId))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }


        public bool UserLogout(string userId, string password)
        {
            OAuth oAuth = new OAuth(userId, password);
            string userQueryRequestUrl = string.Format("/user/logout.json");
            try
            {
                string response = oAuth.Request(userQueryRequestUrl);
                User result = JsonConvert.DeserializeObject<User>(response);
                if (string.Equals(result.ID, userId))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
